package com.example.dianproject.controller;

import com.example.dianproject.entity.Customer;
import com.example.dianproject.service.CustomerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.http.ResponseEntity;
import java.util.List;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;

@Controller
public class CustomerController {
    @Autowired
    private CustomerService customerService;

    @GetMapping("/admin/customers")
    public String listCustomers(Model model) {
        List<Customer> customers = customerService.getAllCustomers();
        model.addAttribute("customers", customers);
        return "admin/templates/customers";
    }

    // 新增：RESTful接口，返回客户列表JSON
    @GetMapping("/api/customers")
    @ResponseBody
    public ResponseEntity<List<Customer>> getCustomersJson() {
        List<Customer> customers = customerService.getAllCustomers();
        return ResponseEntity.ok(customers);
    }

    // 获取客户总数
    @GetMapping("/api/customers/count")
    @ResponseBody
    public ResponseEntity<Long> getCustomerCount() {
        long count = customerService.getCustomerCount();
        return ResponseEntity.ok(count);
    }

    // 新增客户
    @PostMapping("/api/customers")
    @ResponseBody
    public ResponseEntity<Customer> addCustomer(@RequestBody Customer customer) {
        Customer saved = customerService.saveCustomer(customer);
        return ResponseEntity.ok(saved);
    }

    // 编辑客户
    @PutMapping("/api/customers/{customerId}")
    @ResponseBody
    public ResponseEntity<Customer> updateCustomer(@PathVariable Long customerId, @RequestBody Customer customer) {
        customer.setCustomerId(customerId);
        Customer updated = customerService.saveCustomer(customer);
        return ResponseEntity.ok(updated);
    }

    // 删除客户
    @DeleteMapping("/api/customers/{customerId}")
    @ResponseBody
    public ResponseEntity<Void> deleteCustomer(@PathVariable Long customerId) {
        customerService.deleteCustomer(customerId);
        return ResponseEntity.ok().build();
    }
} 